<template>
  <div>
    <!-- 三级分类 -->
    <Category :scene="scene"></Category>
    <el-card style="margin: 10px 0px">
      <!-- 场景0 -->
      <div v-show="scene == 0">
        <el-button
          type="primary"
          size="default"
          icon="Plus"
          :disabled="!categoryStore.c3Id"
          @click="addSpu"
        >
          添加SPU
        </el-button>
        <el-table style="margin: 10px 0px" border :data="records">
          <el-table-column
            label="序号"
            type="index"
            align="center"
            width="80px"
          ></el-table-column>
          <el-table-column
            prop="spuName"
            label="SPU名称"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="description"
            label="SPU描述"
            align="center"
            :show-overflow-tooltip="true"
          ></el-table-column>
          <el-table-column label="SPU操作" align="center">
            <template #="{ row, $index }">
              <el-button
                type="primary"
                size="default"
                icon="Plus"
                title="添加SKU"
                plain
                @click="addSku(row)"
              ></el-button>
              <el-button
                type="warning"
                size="default"
                icon="Edit"
                title="修改SPU"
                plain
                @click="updateSpu(row)"
              ></el-button>
              <el-button
                type="info"
                size="default"
                icon="InfoFilled"
                title="查看SPU"
                plain
                @click="findSku(row)"
              ></el-button>
              <el-popconfirm
                :title="`你确定要删除${row.spuName}吗?`"
                width="200px"
                @confirm="deleteSpu(row)"
              >
                <template #reference>
                  <el-button
                    type="danger"
                    size="default"
                    icon="Delete"
                    title="删除SPU"
                    plain
                  ></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <el-pagination
          @size-change="changeSize"
          @current-change="getHasSPU"
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[3, 5, 7, 9]"
          :size="size"
          :total="total"
          :background="true"
          layout="prev, pager, next, jumper,->,sizes,total"
        ></el-pagination>
      </div>
      <!-- 场景1 添加/修改SPU -->
      <spuForm
        ref="spu"
        v-show="scene == 1"
        @changeScene="changeScene"
      ></spuForm>
      <!-- 场景2 添加SKU -->
      <skuForm
        ref="sku"
        v-show="scene == 2"
        @changeScene="changeScene"
      ></skuForm>
      <!-- dialog对话框 -> 展示已有的SKU数据 -->
      <el-dialog v-model="show" title="SKU列表">
        <el-table border :data="skuArr">
          <el-table-column
            label="SKU名字"
            prop="skuName"
            align="center"
          ></el-table-column>
          <el-table-column
            label="SKU价格(元)"
            prop="price"
            align="center"
          ></el-table-column>
          <el-table-column
            label="SKU重量(克)"
            prop="weight"
            align="center"
          ></el-table-column>
          <el-table-column label="SKU图片" align="center">
            <template #="{ row, $index }">
              <img :src="row.skuDefaultImg" alt="" style="width: 100px" />
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import type {
  HasSpuResponseData,
  Records,
  SpuData,
  SkuInfoData,
  SkuData,
} from '@/api/product/spu/type'
import { ref, watch, nextTick, onBeforeUnmount } from 'vue'
// 引入分类仓库
import useCategoryStore from '@/store/modules/category'
import { ElMessage, type ComponentSize } from 'element-plus'
import { reqHasSpu, reqSkuList, reqRemoveSpu } from '@/api/product/spu'
import skuForm from './skuForm.vue'
import spuForm from './spuForm.vue'
// 场景的数据
/**
 * 0:spu
 * 1:add/update spu
 * 2:add sku
 */
let scene = ref<number>(0)
let currentPage = ref<number>(1)
let pageSize = ref<number>(5)
let records = ref<Records>([])
let total = ref<number>(0)
// 存储全部SKU的数据
let skuArr = ref<SkuData[]>([])
// 控制SKU列表的显示鱼隐藏
let show = ref<boolean>(false)
const size = ref<ComponentSize>('default')
// 获取分类仓库
const categoryStore = useCategoryStore()
const spu = ref()
const sku = ref()

// 监听三级分类id的变化
watch(
  () => categoryStore.c3Id,
  // 有三级分类再发id
  () => {
    if (!categoryStore.c3Id) return
    getHasSPU()
  },
)
// 获取三级分类下全部已有的SPU
const getHasSPU = async (pager = 1) => {
  currentPage.value = pager
  const result: HasSpuResponseData = await reqHasSpu(
    currentPage.value,
    pageSize.value,
    categoryStore.c3Id,
  )
  if (result.code === 200) {
    records.value = result.data.records
    total.value = result.data.total
  }
}
// 分页器下拉菜单发生变化触发
const changeSize = () => {
  getHasSPU()
}
const addSpu = () => {
  // 点击添加SPU按钮，调用子组件方法初始化数据
  spu.value.initAddSpu(categoryStore.c3Id)
  scene.value = 1
}
const updateSpu = (row: any) => {
  spu.value.initHasSpuData(row)
  scene.value = 1
}
// 自定义事件 子->父 scene切换
const changeScene = (obj: any) => {
  scene.value = obj.flag
  // 再次获取已有的SPU
  if (obj.params == 'update') {
    // 更新留在当前页
    getHasSPU(currentPage.value)
  } else {
    // 新增回到首页
    getHasSPU()
  }
}
// 添加SKU按钮的回调
const addSku = (row: SpuData) => {
  // 切换场景为2
  scene.value = 2
  // 调用子组件方法->初始化添加SKu的数据
  sku.value.initSkuData(categoryStore.c1Id, categoryStore.c2Id, row)
}
// 查看当前SPU下的SKU
const findSku = async (row: SpuData) => {
  const result: SkuInfoData = await reqSkuList(row.id as number)
  if (result.code == 200) {
    skuArr.value = result.data
    show.value = true
  }
}
// 删除某个SPU
const deleteSpu = async (row: SpuData) => {
  const result: any = await reqRemoveSpu(row.id as number)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: `删除${row.spuName}成功`,
    })
    nextTick(() => {
      getHasSPU(
        records.value.length > 0 ? currentPage.value : currentPage.value - 1,
      )
    })
  } else {
    ElMessage({
      type: 'error',
      message: `删除${row.spuName}失败`,
    })
  }
}
// 路由组件销毁，清空仓库关于分类的数据
onBeforeUnmount(() => {
  categoryStore.$reset()
})
</script>

<style scoped>
</style>